<?php
// +----------------------------------------------------------------------
// | 多客怪兽框架多平台开发框架
// +----------------------------------------------------------------------
// | Copyright (c) 2021~2024 http://www.dkyx.cc All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 刘泓宾（514660094@qq.com）
// +----------------------------------------------------------------------

namespace app\common\model\platform;

use app\common\model\addon\Addons;
use app\common\model\AdminBaseModel;
use app\common\model\BaseModel;
use hiduoke\services\douyinMinApp\DouyinMinAppServer;
use think\facade\Cache;
use think\Model;

/**
 * 小程序模型
 * Create by :  刘泓宾<514660094@qq.com>
 * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
 * Created on:  2025/5/15 22:18
 */
class PlatformApp extends AdminBaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'platform_app';

    protected $type = array(
        'config'        => 'json',
        'server_config' => 'json',
        'other_data'    => 'json',
        'setting'       => 'json',
        'versions'      => 'json',
    );

    /**
     * 获取平台应用小程序配置
     * @param string $addon_name
     * @param int $plaid
     * @return array|mixed
     */
    public function getPlatformAppConfig($addon_name = '', $appid = 0)
    {
        $appid = $appid ?: get_appid();
        $addon_name = $addon_name ?: get_addon();
        $res = $this->where(['id' => $appid, 'addon_name' => $addon_name])->field('config')->findOrEmpty();
        return $res->config ?? [];
    }

    /**
     * 获取平台详情
     * @param $plaid
     * @return PlatformWxapp|array|mixed|\think\Model|null
     */
    public function getPlatformDetails($plaid)
    {
        $SettingModel = new PlatformSetting();
        $res = $this->where(['plaid' => $plaid])->find();
        $res['api_url'] = url("/h5/api/index", ['p' => $plaid], true, true)->build();
        $res['setting'] = array(
            'pay'      => $SettingModel->where(['key' => 'pay', 'plaid' => $plaid])->find(),
            'transfer' => $SettingModel->where(['key' => 'transfer', 'plaid' => $plaid])->find()
        );
        return $res;
    }

    public function getAddonAttr($value, $data)
    {
        $res = (new Addons())->where('name', $data['addon_name'])->append(['default_url'])->find();
        if ($res) {
            $res = $res->toArray();
            $res['default_url'] = str_replace('plaid=0', 'plaid=' . $data['plaid'], $res['default_url']) . "&appid=" . $data['id'];
            return $res;
        } else {
            return false;
        }
    }

    public function searchAddonAttr($query, $value, $data)
    {
        $addon_names = [];
        $addons = (new Addons())->where('status', 1)->field('name')->select()->toArray();
        foreach ($addons as $key => $value) {
            $addon_names[] = $value['name'];
        }
        $query->where('addon_name', 'in', $addon_names);
    }


    //    public function getVersionsAttr($value, $data)
    //    {
    ////        $auth_type = json_decode($data['server_config'],true)['auth_type'] ?? 0;
    ////        if ($auth_type) {
    ////            if ($data['app_type'] == 'dy') {
    ////                $res = Cache::get('version_app_id_' . $data['id']);
    ////                if (!$res) {
    ////                    $DY = new DouyinMinAppServer($data['id']);
    ////                    $res = $DY->getOpenApi()->versions($DY->get_authorizer_access_token());
    ////                    Cache::tag('dy_version_' . $data['plaid'])->set('version_app_id_' . $data['id'], $res, 7200);
    ////                }
    ////                if ($res['errno'] == 0) {
    ////                    return $res['data'];
    ////                }
    ////            }
    ////        }
    //        return null;
    //    }

    public function getCheckAttr($value, $data)
    {
        if ($data['app_type'] == 'dy') {
            $res = Cache::get('version_app_id_' . $data['id']);
            if (!$res) {
                $DY = new DouyinMinAppServer($data['id']);
                $res = $DY->getOpenApi()->versions($DY->get_authorizer_access_token());
                Cache::tag('dy_version_' . $data['plaid'])->set('version_app_id_' . $data['id'], $res, 7200);
            }
            $check = ['text' => "未知", 'type' => 'info'];
            if ($res['errno'] == 0) {
                $has_publish = $res['data']['audit']['has_publish'] ?? -1;
                $current = $res['data']['current'] ?? null;
                if ($current || $has_publish == 1) {
                    $check = ['text' => "已发布", 'type' => 'success'];
                } else {
                    $audit_status = $res['data']['audit']['status'] ?? -1;
                    if ($audit_status == 0) {
                        $check = ['text' => "审核中", 'type' => 'warning'];
                    } elseif ($audit_status == 2) {
                        $check = ['text' => "不通过", 'type' => 'danger'];
                    } elseif ($audit_status == 3) {
                        $check = ['text' => "撤回审核", 'type' => 'danger'];
                    } else {
                        $check = ['text' => "未审核", 'type' => 'info'];;
                    }
                }
            }
        }
        return $check;
    }

    /**
     * 关联Addons模型
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\model\relation\BelongsTo
     */
    public function addons()
    {
        return $this->belongsTo(Addons::class, 'aid', 'id');
    }

    /**
     * 定义查询范围
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $query
     * @return void
     */
    public function scopeDefault($query) {}

    /**
     * 数据新增前执行
     * Create by :  刘泓宾<514660094@qq.com>
     * @param Model $model
     * @return void
     */
    public static function onBeforeInsert(Model $model) {}
}
